from main.config import driver_path, chrome_options
from selenium import webdriver

from utils.image_util import download_save_img

browser = webdriver.Chrome(executable_path=driver_path, options=chrome_options)
browser.implicitly_wait(5)


def download(url: str):
    browser.get(url)

    # 获取集合名称
    collection_name = browser.find_element_by_css_selector('h1.mhy-collection-info__name').text
    # 查找合集中所有的文章标签
    articles_tab = browser.find_elements_by_css_selector("div.mhy-article-card")

    articles = []  # (name, upadtetime, href)
    for tab in articles_tab:
        upadtetime = tab.find_element_by_css_selector('span').text
        name = tab.find_element_by_css_selector('h3.mhy-article-card__h3').text
        href = tab.find_element_by_css_selector('a.mhy-router-link.mhy-article-card__link').get_attribute('href')
        articles.append((name, upadtetime, href))

    for name, upadtetime, href in articles:
        browser.get(href)
        imgs_tab = browser.find_elements_by_css_selector('div.mhy-img-article > img')
        for i, img_tab in enumerate(imgs_tab):
            img_url = img_tab.get_attribute('large')
            download_save_img(img_url, '{}/{}{}({}).jpg'.format(collection_name, name, upadtetime, i + 1))


if __name__ == '__main__':
    id = '1994249'
    prefix = 'https://www.miyoushe.com/ys/collection/'
    download(prefix + id)
